using LitJson;
using UnityEngine;
using UnityEngine.UI;
namespace CGF
{
    public partial class PanelRecharge : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        private static float queryEndTime = 0;
        private static string queryOrderNo;

        public static void Open()
        {
            UIManagerComponent.instance.OpenUI<PanelRecharge>(UILayer.Normal, RootComponent.instance, false);
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelRecharge>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelRecharge", layer, isFloat);
            BindProperties(transform);

            BtnBack.SetClick(Close);

            for (int i = 0; i < Buttons.switchs.Length; i++)
            {
                Buttons.switchs[i].GetComponentInChildren<Text>().text = $"{I18N.Currency} {Config.Get.RechargeOptions[i]}";
            }

            Placeholder.text = $"{I18N_amount_range.Replace("{min}", Config.Get.RechargeOptions[0].ToString()).Replace("{max}", Config.Get.RechargeOptions[3].ToString())}";
            Prefix.text = I18N.Currency;
            InputField.text = Config.Get.RechargeOptions[0].ToString();

            Buttons.onSwitchChange = index =>
            {
                InputField.text = Config.Get.RechargeOptions[index].ToString();
            };

            BtnConfirm.SetClick(async () =>
            {
                if (string.IsNullOrEmpty(InputField.text))
                {
                    Dialog.Alert(I18N_please_input_amount);
                    return;
                }
                if (int.Parse(InputField.text) < Config.Get.RechargeOptions[0])
                {
                    Dialog.Alert(I18N_can_not_less_min.Replace("{num}", Config.Get.RechargeOptions[0].ToString()));
                    return;
                }
                if (int.Parse(InputField.text) > Config.Get.RechargeOptions[3])
                {
                    Dialog.Alert(I18N_can_not_above_max.Replace("{num}", Config.Get.RechargeOptions[3].ToString()));
                    return;
                }
                JsonData data = new JsonData();
                int amount = int.Parse(InputField.text);
                data["amount"] = amount * 100;//业务服用分做单位
                var res = await Network.Post("/v1/withdrawal/recharge", data);
                if (res.success)
                {
                    JsonData recharge = res.jsonData["data"]["recharge"];
                    string orderNo = recharge["id"].ToString();

                    if (CGFConfig.Instance.ResServerType == EResServerType.TestServer)
                    {
                        PaySuccessCallbackForTestPack(orderNo, (int)data["amount"]);
                        return;
                    }
                    else
                    {
                        switch (CGFConfig.Instance.ReleaseArea)
                        {
                            case EArea.Common:
                                PaySuccessCallbackForTestPack(orderNo, (int)data["amount"]);
                                return;
                        }
                    }

                    JsonData payData = new JsonData();
                    payData["pack"] = Config.Get.PayPack;
                    payData["order_no"] = orderNo;
                    payData["amount"] = amount;
                    payData["account"] = UserInfo.Account;
                    payData["report_url"] = $"{Config.Get.APIBaseUrl}/v1/withdrawal/recharge/callback";
                    payData["sign"] = SignHelper.SignJson(payData, Config.Get.PaySecret);
                    var orderRes = await HttpHelper.PostJson(Config.Get.PayAPI, payData);
                    if (orderRes.success)
                    {
                        JsonData orderData = JsonMapper.ToObject(orderRes.text);
                        if ((int)orderData["code"] == 0 && SignHelper.VerifyJson(orderData, Config.Get.PaySecret))
                        {
                            string payUrl = orderData["url"].ToString();
                            queryOrderNo = orderNo;
                            Application.OpenURL(payUrl);
                        }
                        else
                        {
                            Dialog.Alert(orderData["msg"].ToString());
                        }
                    }

                }
            });

            HotfixLaunch.instance.appFocusAction += OnApplicationFocus;
        }

        private async void PaySuccessCallbackForTestPack(string orderNo, int amount)
        {
            int time = TimeHelper.GetLocalTimestampS();
            string sign = MD5Helper.StringToMD5(amount + orderNo + time + "KeyEqRpbvxuetNKe6yn");
            var callbackRes = await Network.Get($"/v1/withdrawal/recharge/callback?amount={amount}&order_id={orderNo}&time={time}&sign={sign}");
            if (callbackRes.success)
            {
                Dialog.Alert(I18N_recharge_success, Close);
            }
        }

        private void OnApplicationFocus(bool isFocus)
        {
            if (isFocus && !string.IsNullOrEmpty(queryOrderNo))
            {
                queryEndTime = Time.time + 60 * 5; //每次回到游戏继续查新5分钟
                Query();
            }
        }

        private static async void Query()
        {
            if (string.IsNullOrEmpty(queryOrderNo) || Time.time > queryEndTime) return;

            JsonData data = new JsonData();
            data["order_no"] = queryOrderNo;
            var orderRes = await HttpHelper.PostJson(Config.Get.PayQueryAPI, data);
            if (orderRes.success)
            {
                JsonData orderData = JsonMapper.ToObject(orderRes.text);
                if ((int)orderData["code"] == 0 && (bool)orderData["is_paid"])
                {
                    queryOrderNo = null;
                    UserInfo.RefreshWallet();
                    Dialog.Alert(CommAssets.instance.I18N_recharge_success, Close);
                }
                else
                {
                    await CTask.Wait(2);
                    Query();
                }
            }
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            HotfixLaunch.instance.appFocusAction -= OnApplicationFocus;
        }

    }
}
